package com.example.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.BusinessExceptionUtils;
import com.example.dto.TransferMsg;
import com.example.mapper.AccountMapper;
import com.example.mq.sender.IMsgSender;
import com.example.po.AccountPO;
import com.example.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;

/*
@description:
@ClassName AccountServiceImpl
@author chen
@create 2025-08-26 10:58
@Version 1.0
*/
@Slf4j
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, AccountPO> implements AccountService
{
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private IMsgSender msgSender;


    @Override
    public void transfer(String fromAccountId, String toAccountId, BigDecimal transferPrice)
    {
        //1、转账人，账户余额减少
        this.balanceSubtract(fromAccountId, transferPrice);
        //2、投递MQ转账消息
        TransferMsg msg = TransferMsg.builder().
                fromAccountId(fromAccountId).
                toAccountId(toAccountId).
                transferPrice(transferPrice).build();
        this.msgSender.send(msg);
    }

    @Override
    public void balanceAdd(String accountId, BigDecimal price)
    {
        int update = this.accountMapper.balanceAdd(accountId, price);
        if (update != 1)
        {
            throw BusinessExceptionUtils.businessException("更新账号余额失败!");
        }
    }

    /**
     * 减少账户余额
     *
     * @param accountId
     * @param price
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void balanceSubtract(String accountId, BigDecimal price)
    {
        int update = this.accountMapper.balanceSubtract(accountId, price);
        if (update != 1)
        {
            throw BusinessExceptionUtils.businessException("更新账号余额失败!");
        }
    }

}
